using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.Xna.Framework.Graphics;
using System.IO;

namespace Dracham.TileManagement
{
    public class DrachamTexture
    {
        private Texture2D texture;
        private Boolean useTransparency;
        private Int32 transparencyColor;
        private String name;

        #region properties

        public String Name
        {
            get { return name; }
        }

        public Texture2D Texture
        {
            get { return texture; }
        }

        public Boolean UseTransparency
        {
            get { return useTransparency; }
        }

        public Int32 TransparencyColor
        {
            get { return transparencyColor; }
        }

        #endregion

        private DrachamTexture()
        {

        }

        public static DrachamTexture FromXmlNode(XmlNode texture)
        {
            DrachamTexture tt = new DrachamTexture();

            MemoryStream ms = new MemoryStream();
            Byte[] buff = Convert.FromBase64String(texture.FirstChild.Value);
            ms.Write(buff, 0, buff.Length);
            ms.Seek(0, SeekOrigin.Begin);

            tt.transparencyColor = Convert.ToInt32(texture.Attributes["Color"].Value);
            tt.useTransparency = Convert.ToBoolean(texture.Attributes["UseTransparency"].Value);
            tt.name = texture.Attributes["Name"].Value;

            TextureCreationParameters tcp = TextureCreationParameters.Default;
            tcp.Format = SurfaceFormat.Rgba32;
            tcp.Filter = FilterOptions.None;
            tcp.Depth = 32;

            if (tt.useTransparency)
            {
                long a = (tt.transparencyColor & 0xFF000000) >> 24;
                Int32 r = (tt.transparencyColor & 0x000000FF);
                Int32 g = (tt.transparencyColor & 0x0000FF00) >> 8;
                Int32 b = (tt.transparencyColor & 0x00FF0000) >> 16;

                tcp.ColorKey = new Color(Convert.ToByte(r), Convert.ToByte(g), Convert.ToByte(b), Convert.ToByte(a));
            }

            tt.texture = Texture2D.FromFile(Dracham.Device, ms, tcp);

            return tt;
        }
    }
}
